<template>
	<!-- 导出组件 -->
	<lay-layer v-model="visible" :title="`报表导出 - ${routerTitle}`" :shade-opacity="0.5" :shade-close="false" :area="area" :btn="action">
		<div class="flex align-start padding-lg">
			<div class="check-box padding">
				<div class="text-center text-lg padding-bottom-lg padding-top-sm">
					<lay-line contentPosition="center">导出字段</lay-line>
				</div>
				<lay-checkbox-group v-model="checkeds">
					<lay-checkbox v-for="(item, index) in columnList" :value="item.key" name="like" skin="primary" class="display-block">{{item.title}}</lay-checkbox>
				</lay-checkbox-group>
			</div>
			<div class="flex-sub">
				<div class="flex align-center text-green margin-bottom padding-left-lg">
					<lay-icon type="layui-icon-tips-fill"></lay-icon>
					<span class="margin-left-sm">可在列表页面添加搜索条件，导出指定搜索条件的数据。</span>
				</div>
				<div class="padding">
					已选搜索条件：
					<template v-for="(tag, index) of LstKey" :key="`tag-${index}`">
						<lay-tag color="#edeffc" size="lg" style="margin-right: 5px; margin-bottom: 5px;">
							<span class="text-blue">{{tag.name}}</span>
						</lay-tag>
					</template>
					<lay-tag size="lg" style="margin-right: 5px" v-if="!params.LstKey || params.LstKey?.length === 0">
						<span>暂无搜索条件</span>
					</lay-tag>
				</div>
				<lay-json-schema-form ref="formRef" :model="formData" :useCN="true" :schema="formSchema" space="2"></lay-json-schema-form>
			</div>
		</div>
	</lay-layer>
</template>

<script setup>
	import { ref, getCurrentInstance, onMounted } from 'vue';
	import { useRouter } from 'vue-router';
	// import { saveAs } from 'file-saver' //下载插件
	import { useCommonStore } from '@/store/modules/common.js'; //公共数据
	const commonStore = useCommonStore()

	const { proxy } = getCurrentInstance();

	const router = useRouter();
	const routerTitle = ref(router.currentRoute.value.meta.title); //当前路由title

	const props = defineProps({
		//url,导出全部数据是的url
		url: {
			type: String,
			default: ''
		},
		//导出指定选择的数据时的数据
		params: {
			type: Object,
			default: () => {
				return {}
			}
		},
		//搜索条件
		selectData: {
			type: Array,
			default: () => {
				return []
			}
		},
		//搜索组件配置
		schema: {
			type: Object,
			default: () => {
				return {}
			}
		},
		//url参数
		urlParams: {
			type: String,
			default: ''
		},
		//表格配置字段--自定义导出字段
		columnList: {
			type: Array,
			default: () => {
				return []
			}
		}
	});
	const emit = defineEmits(['setExportField']);

	const checkeds = ref([]) //复选框选择的值

	onMounted(() => {
		//默认全选
		props.columnList?.forEach(item => {
			checkeds.value.push(item.key)
		})
	})

	const LstKey = ref([]) //搜索条件
	//设置搜索条件
	async function LstKeyFun() {
		let list = JSON.parse(JSON.stringify(props.params.LstKey || []))
		for (let i = 0; i < list.length; i++) {
			let tagItem = {}
			if (list[i].FieldName === 'RoomID' || list[i].FieldName === 'dd.RoomID') {
				//特殊处理左侧树状食堂导航数据
				let res = await commonStore.getAllRoomList()
				let roomItem = res.find(x => x.ID === list[i].FieldValue)
				list[i].name = `食堂名称：${roomItem.RoomName}`
			} else if (list[i].FieldName === 'DeviceID') {
				//特殊处理左侧树状设备信息数据
				const paramsDevice = {
					limit: 15,
					page: 1,
					LstKey: [{
						FieldName: "ID",
						FieldValue: list[i].FieldValue,
						ConditionalType: "Like"
					}]
				}
				let res = await proxy.$http.device.getDevicePages(paramsDevice)
				if (res.data?.length > 0) list[i].name = `设备信息：${res.data[0]?.DeviceName}(${res.data[0]?.MachineBrandName})`
			} else if (list[i].FieldName === 'DeptID' || list[i].FieldName === 'sd.ID') {
				//特殊处理左侧树状组织架构导航数据
				let res = await commonStore.getAllDepartList()
				let DepartItem = res.find(x => x.id === list[i].FieldValue)
				list[i].name = `组织架构：${DepartItem.name}`
			} else if (list[i].FieldName === 'CateID') {
				//菜品类别下拉选择
				let res = await commonStore.getDishCatetList()
				let DepartItem = res.find(x => x.ID === list[i].FieldValue)
				list[i].name = `菜品类别：${DepartItem.CateName}`
			} else if (list[i].FieldName === 'MealCode') {
				//餐别下拉选择
				let res = commonStore.EMealType
				let DepartItem = res.find(x => x.value === list[i].FieldValue)
				list[i].name = `餐别：${DepartItem.label}`
			} else if (list[i].FieldName === 'DW_Date') {
				//日期下拉选择
				let res = commonStore.EWeek
				let DepartItem = res.find(x => x.value === list[i].FieldValue)
				list[i].name = `日期：${DepartItem.label}`
			} else if (list[i].FieldName === 'isOutDate') {
				//时间状态，是否过期
				let res = [{
						label: '已过期',
						value: 'true'
					},
					{
						label: '未过期',
						value: 'false'
					},
				]
				let DepartItem = res.find(x => x.value === list[i].FieldValue)
				list[i].name = `时间状态：${DepartItem.label}`
			} else if (list[i].FieldName === 'ParentID') {
				//字典类型
				let res = await commonStore.getAllDictList()
				let DepartItem = res.find(x => x.ID === list[i].FieldValue)
				list[i].name = `字典类型：${DepartItem.DictName}`
			} else if (list[i].FieldName === 'LogType') {
				//日志类型
				let res = [{
						Code: 'login',
						Name: '登录日志',
					},
					{
						Code: 'opera',
						Name: '操作日志',
					},
				]
				let DepartItem = res.find(x => x.Code === list[i].FieldValue)
				list[i].name = `日志类型：${DepartItem.Name}`
			} else {
				if (props.schema[list[i].FieldName]?.label) list[i].name = `${props.schema[list[i].FieldName]?.label}：${list[i].FieldValue}`
			}
		}
		LstKey.value = list
	}
	LstKeyFun()

	const loading = ref(false) //laoding
	const formRef = ref(null) //表单ref
	const visible = ref(false);
	const area = ref(['960px', '580px'])

	// 表单数据
	const model = {
		encryption: true, //文件加密
		encryptionPwd: '', //文件加密密码
		fileFormat: 'xlsx', //文件格式
		exportType: '1', //导出方式
		start: 1, //起始位置
		totalNum: 100 //总条数
	};

	const formData = ref(JSON.parse(JSON.stringify(model)));


	//表单配置
	const formSchema = ref({
		encryption: {
			label: '文件加密',
			type: 'radio',
			props: {
				options: [{
						label: "是",
						value: true,
					},
					{
						label: "否",
						value: false,
					}
				],
			},
			//事件集合
			listeners: {
				onChange: (v) => {
					//监听选择事件
					encryptionChange(v);
				},
			},
		},
		encryptionPwd: {
			label: '文件加密密码',
			type: 'input',
			required: true,
			props: {
				type: 'password',
				autocomplete: 'off',
				allowClear: true,
				placeholder: '请输入文件加密密码',
			}
		},
		fileFormat: {
			label: '文件格式',
			type: 'select',
			required: true,
			props: {
				options: [
					// { label: 'Word', value: 'docx' },
					{ label: 'Excel', value: 'xlsx' },
					// { label: 'PDF', value: 'pdf' }
				],
				placeholder: '请选择文件格式',
			}
		},
		exportType: {
			label: '导出方式',
			type: 'radio',
			props: {
				options: [{
						label: "全部数据（最多导出100000条数据）",
						value: '1',
					},
					{
						label: "所选勾选数据",
						value: '0',
					}
				],
			},
			//事件集合
			listeners: {
				onChange: (v) => {
					//监听选择事件
					// exportTypeChange(v);
				},
			},
		},
		start: {
			label: '起始位置',
			type: 'input',
			hidden: true,
			required: false,
			props: {
				type: 'number',
				autocomplete: 'off',
				allowClear: true,
				placeholder: '请输入起始位置',
			}
		},
		totalNum: {
			label: '总条数',
			type: 'input',
			hidden: true,
			required: false,
			props: {
				type: 'number',
				autocomplete: 'off',
				allowClear: true,
				placeholder: '请输入总条数',
			}
		},
	});

	const action = ref([{
			text: '确定',
			callback: () => {
				formRef.value.validate((isValidate, model, errors) => {
					if (isValidate) {
						if (!props.url) return proxy.$msg.err('URL不能为空！')
						if(checkeds.value.length === 0) return proxy.$msg.err('请选择需要导出的字段！')
						if (loading.value) return

						const url = props.url.split('.');
						let urlParamss = props.urlParams ? `${props.urlParams}&export=true` : '?export=true'

						//导出配置
						let ExportConfig = {
							FieldName: 'ExportConfig',
							FieldValue: {
								Prefix: routerTitle.value,	//导出文件名称
								Password: formData.value.encryptionPwd,	//加密密码
								FieldConfigs: [],	//自定义导出字段
							}
						}
						ExportConfig.FieldValue.FieldConfigs = setExportField()	//自定义导出字段
						ExportConfig.FieldValue = JSON.stringify(ExportConfig.FieldValue)
						let params = JSON.parse(JSON.stringify(props.params))

						if(params.LstKey) {
							params.LstKey.push(ExportConfig)
						}else {
							params.LstKey = [ExportConfig]
						}
						if (model.exportType === '0') {
							params.LstKey.push({
								FieldName: "o.ID",
								FieldValue: props.selectData.map(i => i.ID).join(','),
								ConditionalType: "In"
							})
						}

						let loadingIndex = proxy.$msg.loading()
						loading.value = true
						proxy.$http[url[0]][url[1]](params, urlParamss).then(res => {
							loading.value = false
							proxy.$msg.close(loadingIndex) //关闭loading
							if (!res.data) return proxy.$msg.err("数据导出失败！")
							//这边后端会返回一个blob的文件流过来
							// let blob = new Blob([res], {
							// 	type: "charset=utf-8"
							// });
							// let suffix = props.title + '.' + formData.value.fileFormat
							// saveAs(blob, suffix)

							const alink = document.createElement('a');
							alink.style.display = 'none'
							alink.href = res.data;
							alink.download = '';
							document.body.appendChild(alink)
							alink.click();
							URL.revokeObjectURL(alink.href) // 释放URL 对象
							document.body.removeChild(alink)

							proxy.$msg.success("数据导出成功！")
							visible.value = !visible.value;
						}).catch(err => {
							loading.value = false
							proxy.$msg.close(loadingIndex) //关闭loading
						})
					}
				});
			},
		},
		{
			text: '取消',
			callback: () => {
				visible.value = !visible.value;
			},
		},
	]);

	//设置导出字段
	function setExportField() {
		let fieldArr = []
		checkeds.value.forEach(item => {
			let columnItem = props.columnList.find(x => x.key === item)
			// field[item] = columnItem.title
			fieldArr.push({
				FieldName: columnItem.key,
				Alias: columnItem.title,
				// Format: 'yyyy-MM-dd',
				/*ValueMappings: [
                    {
                        FieldValue: 'True',
                        MappedValue: '是'
                    }
                ]*/
			})
		})
		emit('setExportField', checkeds.value, (e) => {
			fieldArr = e
		})
		return fieldArr
	}

	//监听是否加密文本变化
	function encryptionChange(data) {
		if (data) {
			formSchema.value.encryptionPwd.required = true
			formSchema.value.encryptionPwd.hidden = false
		} else {
			formSchema.value.encryptionPwd.hidden = true
			formSchema.value.encryptionPwd.required = false
		}
	}

	//监听导出方式
	function exportTypeChange(data) {
		//显示隐藏起始位置和总条数
		formSchema.value.start.hidden = data == 1 ? true : false
		formSchema.value.start.required = data == 1 ? false : true
		//控制起始位置和总条数是否必填
		formSchema.value.totalNum.hidden = data == 1 ? true : false
		formSchema.value.totalNum.required = data == 1 ? false : true
	}

	function showPolExport() {
		visible.value = !visible.value;
	}

	defineExpose({
		showPolExport
	});
</script>

<style lang="scss" scoped>
	.check-box {
		flex: 0 0 200px;
		border: 1px solid #e1e1e1;
		border-radius: 6px;
		height: 430px;
		margin-right: 20px;
		overflow: auto;

		.display-block {
			display: block;
		}
	}
</style>
